#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
创建支付配置表
"""

import os
import sys
from datetime import datetime

# 添加项目根目录到路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app import create_app, db
from sqlalchemy import text

def upgrade():
    """升级数据库：创建支付配置表"""
    app = create_app()
    
    with app.app_context():
        print("🔄 开始创建支付配置表...")
        
        try:
            with db.engine.connect() as conn:
                # 创建支付配置表
                conn.execute(text("""
                    CREATE TABLE IF NOT EXISTS payment_configs (
                        id INTEGER PRIMARY KEY AUTO_INCREMENT,
                        name VARCHAR(100) NOT NULL COMMENT '配置名称',
                        payment_method VARCHAR(20) NOT NULL COMMENT '支付方式: wechat, alipay',
                        is_enabled BOOLEAN DEFAULT TRUE COMMENT '是否启用',
                        
                        -- 微信支付配置
                        wechat_app_id VARCHAR(100) NULL COMMENT '微信应用ID',
                        wechat_mch_id VARCHAR(100) NULL COMMENT '微信商户号',
                        wechat_api_key VARCHAR(256) NULL COMMENT '微信API密钥',
                        wechat_cert_path VARCHAR(255) NULL COMMENT '微信证书路径',
                        wechat_key_path VARCHAR(255) NULL COMMENT '微信私钥路径',
                        wechat_notify_url VARCHAR(255) NULL COMMENT '微信支付回调地址',
                        
                        -- 支付宝配置（预留）
                        alipay_app_id VARCHAR(100) NULL COMMENT '支付宝应用ID',
                        alipay_private_key TEXT NULL COMMENT '支付宝私钥',
                        alipay_public_key TEXT NULL COMMENT '支付宝公钥',
                        alipay_notify_url VARCHAR(255) NULL COMMENT '支付宝回调地址',
                        
                        -- 通用配置
                        timeout_seconds INTEGER DEFAULT 1800 COMMENT '支付超时时间(秒)',
                        max_retry_times INTEGER DEFAULT 3 COMMENT '最大重试次数',
                        
                        -- 环境配置
                        is_sandbox BOOLEAN DEFAULT FALSE COMMENT '是否沙箱环境',
                        
                        -- 时间戳
                        created_at DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
                        
                        INDEX idx_payment_method (payment_method),
                        INDEX idx_is_enabled (is_enabled),
                        UNIQUE KEY uk_name (name)
                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='支付配置表'
                """))
                
                # 插入默认的微信支付配置
                conn.execute(text("""
                    INSERT INTO payment_configs (
                        name, payment_method, is_enabled,
                        wechat_notify_url, timeout_seconds, is_sandbox
                    ) VALUES (
                        '默认微信支付配置', 'wechat', FALSE,
                        'http://127.0.0.1:5000/api/v1/payments/wechat/notify', 1800, TRUE
                    ) ON DUPLICATE KEY UPDATE 
                        name = name
                """))
                
                conn.commit()
            
            print("✅ 支付配置表创建成功")
            
        except Exception as e:
            print(f"❌ 迁移失败: {e}")
            raise

def downgrade():
    """降级数据库：删除支付配置表"""
    app = create_app()
    
    with app.app_context():
        print("🔄 开始删除支付配置表...")
        
        try:
            with db.engine.connect() as conn:
                conn.execute(text("DROP TABLE IF EXISTS payment_configs"))
                conn.commit()
            
            print("✅ 支付配置表删除成功")
            
        except Exception as e:
            print(f"❌ 回滚失败: {e}")
            raise

if __name__ == '__main__':
    import sys
    if len(sys.argv) > 1 and sys.argv[1] == 'downgrade':
        downgrade()
    else:
        upgrade() 